
package com.be.beadmin.product.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.design.dto.input.StandFileInfoDto;
import com.be.beadmin.design.entity.StandFileInfo;
import com.be.beadmin.design.repository.StandFileInfoRepository;
import com.be.beadmin.design.service.StandFileInfoService;
import com.be.beadmin.product.dto.input.GuideBookFileInfoDto;
import com.be.beadmin.product.dto.output.GuideBookFileInfoEx;
import com.be.beadmin.product.entity.GuideBookFileInfo;
import com.be.beadmin.product.entity.GuideBookFileInfo_;
import com.be.beadmin.product.mapper.GuideBookFileInfoMapper;
import com.be.beadmin.product.mapper.GuideBookFileInfoMapperEx;
import com.be.beadmin.product.repository.GuideBookFileInfoRepository;
import com.be.beadmin.product.service.GuideBookFileInfoService;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.project.entity.BatchProduct;
import com.be.beadmin.project.repository.BatchProductRepository;
import com.be.beadmin.service.impl.MinioService;
import com.be.beadmin.service.service.SerialNumberService;
import com.google.common.io.ByteStreams;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @description 服务实现
* @author cms
* @date 2023-09-19
**/
@Service
@RequiredArgsConstructor
public class GuideBookFileInfoServiceImpl implements GuideBookFileInfoService {

    @Autowired
    private  GuideBookFileInfoRepository guideBookFileInfoRepository;

    @Autowired
    private StandFileInfoRepository standFileInfoRepository;

    @Autowired
    private StandFileInfoService standFileInfoService;

    @Autowired
    private BatchProductRepository batchProductRepository;
    @Autowired
    private  GuideBookFileInfoMapper guideBookFileInfoMapper;
    @Autowired
    private  GuideBookFileInfoMapperEx guideBookFileInfoExMapper;

    @Autowired
    private SerialNumberService serialNumberService;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    private final String bucketName = "guidebookfile";


    @Override
    public Page<GuideBookFileInfoEx> getGuideBookFileInfoByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<GuideBookFileInfo> page = guideBookFileInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(GuideBookFileInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(GuideBookFileInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<GuideBookFileInfoEx> page1 = page.map(guideBookFileInfoExMapper::toEntity);
        return page1;
    }


    @Override
    public List<GuideBookFileInfoEx> getGuideBookFileInfoBybatchProductId(String batchProductId) {

        BatchProduct batchProduct = batchProductRepository.findBatchProductById(batchProductId);

        List<GuideBookFileInfoEx> res;

        if (batchProduct.getIsStandard() == 1) {
            List<StandFileInfo> standGuideFiles = standFileInfoRepository.findStandFileInfoByStandTypeCodeAndCategoryAndDelete(batchProduct.getStandardProductCode(), "作业指导书", 0);
            res = standGuideFiles.stream().map(standFileInfo -> {
                GuideBookFileInfoEx guideBookFile = new GuideBookFileInfoEx();
                guideBookFile.setGuideFileName(standFileInfo.getFileName());
                guideBookFile.setGuideFileCode(standFileInfo.getFileCode());
                guideBookFile.setBucketName(standFileInfo.getBucketName());
                guideBookFile.setInstruction(standFileInfo.getMemo());
                guideBookFile.setUploaderId(standFileInfo.getCreateId());
                guideBookFile.setUploaderName(standFileInfo.getCreateName());
                guideBookFile.setUploadTime(standFileInfo.getCreateTime());
                return guideBookFile;
            }).collect(Collectors.toList());

        }else{
            res = guideBookFileInfoRepository.findGuideBookFileInfoByBatchProductIdAndDelete(batchProductId,0).stream().map(guideBookFileInfoExMapper::toEntity).collect(Collectors.toList());
        }
        return res;

    }

    @Override
    public void addGuideBookFileInfo(GuideBookFileInfoDto guideBookFileInfoDto) {
            GuideBookFileInfo result = guideBookFileInfoRepository.findGuideBookFileInfoByIdAndDelete(guideBookFileInfoDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("GuideBookFileInfo不存在,请重新查询");
            }
            GuideBookFileInfo guideBookFileInfo = guideBookFileInfoMapper.toEntity(guideBookFileInfoDto);
            guideBookFileInfoRepository.save(guideBookFileInfo);
    }

    @Override
    public void updateGuideBookFileInfo(GuideBookFileInfoDto guideBookFileInfoDto) {
            GuideBookFileInfo guideBookFileInfo = guideBookFileInfoRepository.findGuideBookFileInfoById(guideBookFileInfoDto.getId());
            guideBookFileInfo = guideBookFileInfoMapper.toEntity(guideBookFileInfoDto);
            guideBookFileInfoRepository.save(guideBookFileInfo);
    }


    @Override
    public void delGuideBookFileInfo(String id) {
        GuideBookFileInfo guideBookFileInfo = guideBookFileInfoRepository.findGuideBookFileInfoById(id);
        guideBookFileInfo.setDelete(1);
        guideBookFileInfoRepository.save(guideBookFileInfo);
    }

    @Override
    public void delGuideBookFileInfos (List<String> ids) { }



    @Deprecated
    @Transactional
    @Override
    public void uploadGuideBookFileInfo(String uploaderId,String uploaderName,Date uploadTime,String instruction,MultipartFile[] multipartFiles){

        //附件相关
        try {
            if(multipartFiles != null) {
                for (MultipartFile multipartFile : multipartFiles){
                    GuideBookFileInfo guideBookFileInfo = new GuideBookFileInfo();
                    guideBookFileInfo.setUploaderId(uploaderId);
                    guideBookFileInfo.setUploaderName(uploaderName);
                    guideBookFileInfo.setUploadTime(uploadTime);
                    guideBookFileInfo.setInstruction(instruction);
                    guideBookFileInfo.setGuideFileCode(serialNumberService.getNextSnByCode("FileCode"));
                    guideBookFileInfo.setGuideFileName(multipartFile.getOriginalFilename());
                    guideBookFileInfo.setBucketName(bucketName);
                    String uploadFileName = guideBookFileInfo.getGuideFileCode()+"+"+guideBookFileInfo.getGuideFileName();

                    if (!minioUtil.bucketExists(bucketName)){
                        minioUtil.createBucketName(bucketName);
                    }

                    String preview_url = minioUtil.uploadFile2(multipartFile,uploadFileName,bucketName);
                    guideBookFileInfo.setFileUrl(preview_url);
                    guideBookFileInfoRepository.save(guideBookFileInfo);
                }
            }
        } catch (Exception e) {
            throw new BeadminException("上传失败");
        }

    }

    @Transactional
    @Override
    public void uploadGuideBookFileInfo(GuideBookFileInfoDto guideBookFileInfoDto, MultipartFile[] multipartFiles) {
        //附件相关
        try {
            if(multipartFiles != null) {
                for (MultipartFile multipartFile : multipartFiles){
                    GuideBookFileInfo guideBookFileInfo = new GuideBookFileInfo();
                    guideBookFileInfo.setBatchProductId(guideBookFileInfoDto.getBatchProductId());
                    guideBookFileInfo.setUploaderId(guideBookFileInfoDto.getUploaderId());
                    guideBookFileInfo.setUploaderName(guideBookFileInfoDto.getUploaderName());
                    guideBookFileInfo.setUploadTime(guideBookFileInfoDto.getUploadTime());
                    guideBookFileInfo.setInstruction(guideBookFileInfoDto.getInstruction());
                    guideBookFileInfo.setGuideFileCode(serialNumberService.getNextSnByCode("FileCode"));
                    guideBookFileInfo.setGuideFileName(multipartFile.getOriginalFilename());
                    guideBookFileInfo.setBucketName(bucketName);
                    String uploadFileName = guideBookFileInfo.getGuideFileCode()+"+"+guideBookFileInfo.getGuideFileName();

                    if (!minioUtil.bucketExists(bucketName)){
                        minioUtil.createBucketName(bucketName);
                    }

                    String preview_url = minioUtil.uploadFile2(multipartFile,uploadFileName,bucketName);
                    guideBookFileInfo.setFileUrl(preview_url);
                    guideBookFileInfoRepository.save(guideBookFileInfo);
                }
            }
            BatchProduct batchProduct = batchProductRepository.findBatchProductByIdAndDelete(guideBookFileInfoDto.getBatchProductId(), 0);
            batchProduct.setIsGuideBookUploaded(batchProduct.getIsGuideBookUploaded()+1);
            batchProductRepository.save(batchProduct);
        } catch (Exception e) {
            throw new BeadminException("上传失败");
        }
    }


    @Override
    public String getGuideBookFileInfoPreviewUrl(GuideBookFileInfoDto guideBookFileInfoDto) {

        BatchProduct batchProduct = batchProductRepository.findBatchProductById(guideBookFileInfoDto.getBatchProductId());

        String previewUrl;
        try {

            if (batchProduct.getIsStandard() == 1){

                // 标准柜获取url
                StandFileInfoDto standFileInfoDto = new StandFileInfoDto();
                standFileInfoDto.setFileCode(guideBookFileInfoDto.getGuideFileCode());
                standFileInfoDto.setFileName(guideBookFileInfoDto.getGuideFileName());
                standFileInfoDto.setBucketName(guideBookFileInfoDto.getBucketName());
                standFileInfoDto.setVersion(1);
                previewUrl = standFileInfoService.getPreviewUrl(standFileInfoDto);

            }else{
                // 非标准柜获取url
                String fileCode = guideBookFileInfoDto.getGuideFileCode();
                String fileName = guideBookFileInfoDto.getGuideFileName();
                String FileName = fileCode+"+"+fileName ;
                previewUrl = minioUtil.getPreviewFileUrl(guideBookFileInfoDto.getBucketName(),FileName);

            }

        } catch (Exception e) {
            throw new BeadminException("获取失败");
        }
        return previewUrl;
    }

    @Override
    public void downloadGuideBookFile(GuideBookFileInfoDto guideBookFileInfoDto, HttpServletResponse response) {


        if (guideBookFileInfoDto.getId() == null ||  guideBookFileInfoDto.getId().isEmpty()){

            // 标准柜体下载指导书
            StandFileInfo standGuideFile = standFileInfoRepository.findStandFileInfoByFileCode(guideBookFileInfoDto.getGuideFileCode());
            standFileInfoService.downloadStandFile(standGuideFile.getId(),response);


        }else{
            // 非标准柜体下载指导书
            try {
                GuideBookFileInfo guideBookFileInfo = guideBookFileInfoRepository.findGuideBookFileInfoByIdAndDelete(guideBookFileInfoDto.getId(),0);

                String bucketName = guideBookFileInfo.getBucketName();
                String fileName = guideBookFileInfo.getGuideFileName();
                String fileCode = guideBookFileInfo.getGuideFileCode();
                String downloadFileName= fileCode+"+"+fileName;
                InputStream inputStream = minioService.downloadOne(bucketName, downloadFileName);
                response.addHeader("Accept-Ranges", "bytes");
                response.addHeader("Content-disposition", "attachment;filename= "+fileName);
                response.addHeader("Content-Type", "text/plain;charset=utf-8");
                response.addHeader("Pragma","No-cache");
                response.addHeader("Cache-Control","No-cache");
                ServletOutputStream os = response.getOutputStream();

                ByteStreams.copy(inputStream, os);
                os.flush();
            } catch (Exception e) {
                throw new BeadminException("文件下载失败");
            }

        }

    }

}

